<template>
  <div class="container d-flex flex-column justify-content-center align-items-center" style="height:100vh;">
    <h1 style="color:#4AA4B4;">GDD宠物馆</h1>
    <div class="row" style="width:100%;justify-content:center;">
      <div class="col-12 col-sm-12 col-md-10 col-lg-8 col-xl-6" style="border:1px solid #dedede;border-radius:0.5em;padding: 2em 2em;">
        <el-form ref="modifyPasswordForm"
                 :model="modifyPasswordForm"
                 :rules="modifyPasswordFormRules"
                 :status-icon="true"
                 label-width="100px"
                 label-position="left"
                 size="medium">
          <el-form-item label="收件邮箱" prop="receiver">
            <el-row>
              <el-col :xs="24" :sm="16" :md="16" :lg="16" :xl="16">
                <el-input v-model="modifyPasswordForm.receiver" placeholder="请输入收件邮箱"></el-input>
              </el-col>
              <el-col :xs="{span: 24, offset: 0}"
                      :sm="{span: 7, offset: 1}"
                      :md="{span: 7, offset: 1}"
                      :lg="{span: 7, offset: 1}"
                      :xl="{span: 7, offset: 1}"
                      style="text-align:right;">
                <el-button v-if="waitSeconds===cycleSeconds"
                           :disabled="emailSubmitDisabled||!modifyPasswordForm.receiver"
                           style="width:100%;" @click="sendEmail">获取验证码
                </el-button>
                <el-button v-else>{{waitSeconds}}秒</el-button>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="验证码" prop="code">
            <el-input v-model="modifyPasswordForm.code" placeholder="请输入邮箱"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="pw">
            <el-input type="password" v-model="modifyPasswordForm.pw" placeholder="请输入密码"></el-input>
          </el-form-item>
          <el-form-item label="重复密码" prop="rePw">
            <el-input type="password" v-model="modifyPasswordForm.rePw" placeholder="请输入密码"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="medium"
                       :disabled="formSubmitDisabled"
                       @click="submitForm('modifyPasswordForm')"
                       style="margin:2px 0px;">
              修改密码
            </el-button>
            <el-button size="medium"
                       :disabled="formSubmitDisabled"
                       style="margin:2px 0px;">
              <router-link to="/login">登陆</router-link>
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
  import md5 from 'js-md5';

  export default {
    name: 'ModifyPassword',
    data() {
      /**
       * 自定义表单字段校验方法
       */
      let compareToPassword = (rule, value, callback) => {
        if (value && value !== this.modifyPasswordForm.pw) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      };
      return {
        emailSubmitDisabled: false, // 默认启用获取验证码按钮
        formSubmitDisabled: false, // 默认启动表单提交
        cycleSeconds: 30, // 等待时间周期
        waitSeconds: 30, // 剩余等待时间
        modifyPasswordForm: {
          category: 0, // 忘记密码模块通过邮箱找回密码功能标识
          receiver: null, // 收件邮箱
          code: null, // 验证码
          password: null, pw: null,
          rePw: null,
        },
        modifyPasswordFormRules: {
          receiver: [
            {required: true, message: '请输入邮箱', trigger: 'blur'},
            {type: 'email', message: '邮箱格式错误', trigger: ['blur', 'change']}
          ],
          code: [
            {required: true, message: '请输入验证码', trigger: 'blur'},
            {pattern: '^[A-Za-z0-9]{4}$', message: '验证码格式错误', trigger: ['blur', 'change']}
          ],
          pw: [
            {required: true, message: '请输入密码', trigger: 'blur'},
            {pattern: '^[a-zA-Z]\\w{5,9}$', message: '密码格式错误', trigger: ['blur', 'change']}
          ],
          rePw: [
            {required: true, message: '请再次输入密码', trigger: 'blur'},
            {validator: compareToPassword, trigger: ['blur', 'change']}
          ],
        },
      }
    },
    methods: {
      /**
       * 发送验证码到指定邮箱
       */
      sendEmail() {
        // 校验receiver字段
        this.$refs['modifyPasswordForm'].validateField('receiver', (msg) => {
          if(!msg){
            // 获取验证码倒计时
            const calculateWaitSeconds = setInterval(() => {
              this.waitSeconds -= 1;
              if (this.waitSeconds === 0) {
                clearInterval(calculateWaitSeconds); // 取消倒计时
                this.waitSeconds = this.cycleSeconds; // 重置计时
              }
            }, 1000);
            // 获取验证码
            this.$postRequest('/gdd/email/send', this.modifyPasswordForm).then(response => {
              if (response.code === 0) {
                this.emailSubmitDisabled = true;
                clearInterval(calculateWaitSeconds);
                this.waitSeconds = this.cycleSeconds;
                this.$message.success('验证码发送成功，请注意查收！');
              } else {
                this.formSubmitDisabled = false;
                this.emailSubmitDisabled = false;
                clearInterval(calculateWaitSeconds);
                this.waitSeconds = this.cycleSeconds;
              }
            });
          } else {
            this.$message.warning('邮箱格式错误');
          }
        });
      },
      /**
       * 提交表单
       */
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.formSubmitDisabled = true;
            sessionStorage.setItem('pw', this.modifyPasswordForm.pw);
            this.modifyPasswordForm.password = md5(this.modifyPasswordForm.pw);
            this.modifyPasswordForm.pw = 'abc12345';
            this.modifyPasswordForm.rePw = 'abc12345';
            this.$postRequest('/gdd/user/modifyPassword', this.modifyPasswordForm).then(response => {
              if (response.code === 0) {
                sessionStorage.clear();
                this.$message.success('修改成功!');
                setTimeout(() => {
                  this.$router.replace('/login');
                }, 800);
              } else {
                this.formSubmitDisabled = false;
                this.modifyPasswordForm.pw = sessionStorage.getItem('pw');
                this.modifyPasswordForm.rePw = sessionStorage.getItem('pw');
              }
            });
          } else {
            this.formSubmitDisabled = false;
            return false;
          }
        });
      }
    }
  }
</script>

<style scoped>
  form a {
    color: #999999;
    text-decoration: none;
  }
  form a:hover {
    text-decoration: none;
  }
</style>
